<template>
	<!-- 搜索栏 -->
	<view class="search_area">
		<view class="search_asset">
			<uni-search-bar v-model="searchValue" @confirm="search" @input="onSearchInput" @clear="clearSearch"
				placeholder="请输入搜索的文件" cancel-button="none" clear-button="always">
				<template v-slot:searchIcon>
					<uni-icons color="#999999" size="18" type="search" />
				</template>
				<template v-slot:clearIcon>
					<uni-icons color="#999999" size="18" type="clear" />
				</template>
			</uni-search-bar>
		</view>
	</view>

	<!-- 文件列表 -->
	<view class="file-list">
		<view class="file-item" v-for="(file, index) in displayFiles" :key="index">
			<!-- 文件图标 - 根据文件类型显示不同图标 -->
			<uni-icons :size="30" :type="getFileIcon(file.name)"></uni-icons>

			<!-- 文件名 -->
			<view class="file-name" @click="handlePreview(file)">{{ file.name }}</view>

			<!-- 文件信息：上传者、大小、上传时间等 -->
			<view class="file_info">
				<view>由 {{file.uploader}} 上传</view>
			</view>

			<!-- 操作按钮组 -->
			<view class="actions">
				<uni-icons type="settings" size="25" color="#666" @click="showFileOptions(file)" />
			</view>
		</view>
	</view>

	<!-- 文件操作菜单弹窗 -->
	<uni-popup ref="fileOptionsPopup" type="bottom">
		<view class="popup-content">
			<view class="popup-title">文件操作</view>
			<view class="popup-item" @click="handleRename">
				<uni-icons type="compose" size="20" />
				<text>重命名</text>
			</view>
			<view class="popup-item" @click="handleMove">
				<uni-icons type="forward" size="20" />
				<text>移动到</text>
			</view>
			<view class="popup-item warning" @click="confirmDelete">
				<uni-icons type="trash" size="20" />
				<text>删除</text>
			</view>
			<view class="popup-cancel" @click="closeFileOptions">取消</view>
		</view>
	</uni-popup>
	<!-- 上传进度提示 -->
	<uni-popup ref="uploadProgress" type="message">
		<uni-popup-message type="success" :message="uploadStatus" />
	</uni-popup>

	<!-- 增加文件的按钮 -->
	<view class="add-button" @click="chooseFile">
		<uni-icons type="plus" size="30" color="#fff" />
	</view>

</template>

<script>
	import api from "@/api/api.js";
	import http from '/api/http.js';

	export default {

		data() {
			return {
				folderName: '',
				files: [],
				displayFiles: [], // 用于显示的文件列表（考虑搜索筛选后的结果）
				searchValue: '',
				currentFile: null,
				uploadStatus: '',
				projectId: null,
			};
		},

		onLoad(options) {
			this.projectId = Number(options.fileProjectId);
			this.folderName = options.folderName;
			this.fetchFiles(this.projectId);
			uni.setNavigationBarTitle({
				title: this.folderName
			});
		},

		methods: {
			// 文件列表获取
			async fetchFiles(projectId) {
				try {
					const res = await api.listFiles({
						projectId
					});
					this.files = res.data.data.map(file => ({
						name: file.fileName,
						uploader: file.uploadedBy,
						id: file.fileId,
						size: file.fileSize,
						uploadTime: file.uploadTime,
						url: file.fileUrl
					}));
					this.displayFiles = [...this.files];
				} catch (error) {
					console.error('获取文件列表失败:', error);
					uni.showToast({
						title: '获取文件列表失败',
						icon: 'none'
					});
				}
			},

			// 搜索相关方法
			onSearchInput(e) {
				this.searchValue = e;
				this.search();
			},

			search() {
				const query = this.searchValue.toLowerCase();
				this.displayFiles = this.files.filter(file =>
					file.name.toLowerCase().includes(query)
				);
			},

			clearSearch() {
				this.searchValue = '';
				this.displayFiles = [...this.files];
			},

			// 文件图标判断
			getFileIcon(fileName) {
				const extension = fileName.split('.').pop().toLowerCase();
				const iconMap = {
					pdf: 'pdf',
					doc: 'file-word',
					docx: 'file-word',
					xls: 'file-excel',
					xlsx: 'file-excel',
					jpg: 'image',
					jpeg: 'image',
					png: 'image',
					gif: 'image'
				};
				return iconMap[extension] || 'file-text';
			},
			async handlePreview(file) {
				uni.showModal({
					title: '提示:',
					content: "由于微信小程序的限制，我们并不能直接在小程序中下载照片以外的文件，但我们为您提供了基本的预览。如果您想下载，请将下载下来的文件后缀改为文件原本的后缀！ ",
					success: () => {
						this.previewFile(file)
					}
				})
			},
			async previewFile(file) {
				try {
					// 判断是否为图片
					const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
					const fileExt = file.name.split('.').pop().toLowerCase();
					const isImage = imageExtensions.includes(fileExt);
					if (isImage) {
						//TODO:改ip
						// 使用图片预览
						uni.previewImage({
							urls: [`http://192.168.12.169:8080/api/file/download/${file.id}`],
							current: 0,
							success: () => {
								console.log('图片预览成功');
							},
							fail: (error) => {
								console.error('图片预览失败:', error);
								uni.showToast({
									title: '图片预览失败',
									icon: 'none'
								});
							}
						});
						return;
					}

					uni.showLoading({
						title: '准备预览...'
					});

					// 获取文件类型
					const fileType = this.getFileExtension(file.name);
					//TODO:改ip
					// 1. 首先下载文件
					const downloadRes = await uni.downloadFile({
						url: `http://192.168.12.169:8080/api/file/download/${file.id}`,
						header: {
							'X-Access-Token': wx.getStorageSync('WeTeamToken')
						}
					});

					if (downloadRes.statusCode !== 200) {
						throw new Error('文件下载失败');
					}

					// 2. 使用系统打开文件进行预览
					await uni.openDocument({
						filePath: downloadRes.tempFilePath,
						fileType: fileType, // 指定文件类型
						showMenu: true,
						success: () => {
							console.log('打开文档成功');
						},
						fail: (error) => {
							console.error('打开文档失败:', error);
							// 预览失败时，提供下载选项
							uni.showModal({
								title: '提示',
								content: '当前文件类型不支持预览，是否下载到本地？',
								success: (res) => {
									if (res.confirm) {
										// 保存文件
										uni.saveFile({
											tempFilePath: downloadRes.tempFilePath,
											success: (saveRes) => {
												uni.showToast({
													title: '文件已保存',
													icon: 'success'
												});
											},
											fail: () => {
												uni.showToast({
													title: '保存失败',
													icon: 'none'
												});
											}
										});
									}
								}
							});
						}
					});

				} catch (error) {
					console.error('预览失败:', error);
					uni.showToast({
						title: error.message || '预览失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 获取文件扩展名
			getFileExtension(fileName) {
				const ext = fileName.split('.').pop().toLowerCase();
				// 微信小程序支持的文件类型映射
				const supportedTypes = {
					'pdf': 'pdf',
					'doc': 'doc',
					'docx': 'doc',
					'xls': 'xls',
					'xlsx': 'xls',
					'ppt': 'ppt',
					'pptx': 'ppt',
					'txt': 'txt'
				};
				return supportedTypes[ext] || '';
			},
			// 文件操作菜单
			showFileOptions(file) {
				this.currentFile = file;
				this.$refs.fileOptionsPopup.open();
			},

			closeFileOptions() {
				this.$refs.fileOptionsPopup.close();
			},

			// 文件上传相关方法
			async chooseFile() {
				try {
					const res = await new Promise((resolve, reject) => {
						wx.chooseMessageFile({
							count: 1,
							type: 'file',
							success: resolve,
							fail: reject
						});
					});

					const file = res.tempFiles[0];
					// 检查文件名长度
					if (file.name.length > 50) {
						throw new Error('文件名不能超过50个字符');
					}

					// 检查文件大小
					if (file.size > 1 * 1024 * 1024 * 1024) { // 1GB限制
						throw new Error('文件大小不能超过1GB');
					}

					this.uploadStatus = '准备上传...';
					this.$refs.uploadProgress.open();



					await this.uploadFile(file);
				} catch (error) {
					console.error('选择文件失败:', error);
					uni.showToast({
						title: error.message || '选择文件失败',
						icon: 'none'
					});
				}
			},

			async uploadFile(file) {
				try {
					this.uploadStatus = '上传中...';
					//TODO:改ip
					// 上传文件到服务器
					const uploadRes = await uni.uploadFile({
						url: 'http:/192.168.12.169:8080/api/file/uploadFile',
						filePath: file.path,
						name: 'file',
						formData: {
							projectId: this.projectId,
							fileName: file.name
						},
						header: {
							'X-Access-Token': wx.getStorageSync('WeTeamToken')
						}
					});

					if (uploadRes.statusCode !== 200) {
						throw new Error('文件上传失败');
					}

					this.uploadStatus = '上传成功!';
					setTimeout(() => {
						this.$refs.uploadProgress.close();
					}, 1500);

					// 刷新文件列表
					await this.fetchFiles(this.projectId);

					uni.showToast({
						title: '文件上传成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('上传文件失败:', error);
					this.uploadStatus = '上传失败';
					uni.showToast({
						title: '文件上传失败',
						icon: 'none'
					});
				}
			},

			// 文件删除
			async confirmDelete() {
				if (!this.currentFile) return;

				try {
					await new Promise((resolve, reject) => {
						uni.showModal({
							title: '确认删除',
							content: `是否确认删除文件"${this.currentFile.name}"？`,
							success: (res) => {
								if (res.confirm) {
									resolve();
								} else {
									reject(new Error('用户取消'));
								}
							}
						});
					});

					await this.deleteFile(this.currentFile.id);
				} catch (error) {
					if (error.message !== '用户取消') {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				} finally {
					this.closeFileOptions();
				}
			},

			async deleteFile(fileId) {
				try {
					await api.deleteFile({
						fileId
					});

					// 从列表中移除
					this.files = this.files.filter(f => f.id !== fileId);
					this.displayFiles = this.displayFiles.filter(f => f.id !== fileId);

					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('删除文件失败:', error);
					throw error;
				}
			},


			// 重命名文件
			async handleRename() {
				if (!this.currentFile) return;

				try {
					// 分离文件名和后缀
					const lastDotIndex = this.currentFile.name.lastIndexOf('.');
					const fileName = lastDotIndex > -1 ? this.currentFile.name.substring(0, lastDotIndex) : this
						.currentFile.name;
					const fileExt = lastDotIndex > -1 ? this.currentFile.name.substring(lastDotIndex) : '';

					const result = await new Promise((resolve, reject) => {
						uni.showModal({
							title: '重命名文件',
							editable: true,
							placeholderText: '请输入新文件名',
							content: fileName, // 只显示文件名部分
							success: (res) => {
								if (res.confirm) {
									const newName = res.content.trim();
									if (!newName) {
										uni.showToast({
											title: '文件名不能为空',
											icon: 'none'
										});
										reject(new Error('文件名为空'));
										return;
									}
									// 检查文件名是否包含非法字符
									const illegalChars = /[\\/:*?"<>|]/;
									if (illegalChars.test(newName)) {
										uni.showToast({
											title: '文件名不能包含特殊字符',
											icon: 'none'
										});
										reject(new Error('文件名包含非法字符'));
										return;
									}
									if (newName.length > 30) {
										uni.showToast({
											title: '文件名不能超过30字符',
											icon: 'none'
										});
										reject(new Error('文件名超过30字符'));
										return;
									}

									resolve(newName + fileExt); // 保持原来的后缀
								} else {
									reject(new Error('用户取消'));
								}
							}
						});
					});

					// 调用重命名API
					await api.renameFile({
						fileId: this.currentFile.id,
						newFileName: result
					});

					// 更新本地文件列表
					const index = this.files.findIndex(f => f.id === this.currentFile.id);
					if (index !== -1) {
						this.files[index].name = result;
						this.displayFiles = [...this.files];
					}

					uni.showToast({
						title: '重命名成功',
						icon: 'success'
					});
				} catch (error) {
					if (error.message !== '用户取消') {
						console.error('重命名失败:', error);
						uni.showToast({
							title: error.message || '重命名失败',
							icon: 'none'
						});
					}
				} finally {
					this.closeFileOptions();
				}
			},

			// 移动文件
			async handleMove() {

				if (!this.currentFile) return;

				try {
					// 获取可用的目标文件夹列表
					const foldersRes = await api.listProjects({
						teamId: wx.getStorageSync('TheChoosenTeam').teamId
					})

					const folders = foldersRes.data.data.filter(f => f.projectId !== this.projectId)

					// 显示文件夹选择器
					const result = await new Promise((resolve, reject) => {
						uni.showActionSheet({
							itemList: folders.map(f => f.projectName),
							success: (res) => {
								resolve(folders[res.tapIndex]);
							},
							fail: () => {
								reject(new Error('用户取消'));
							}
						});
					});

					// 调用移动文件API
					await api.moveFile({
						projectId: result.projectId,
						fileId: this.currentFile.id
					});

					// 从当前列表中移除
					this.files = this.files.filter(f => f.id !== this.currentFile.id);
					this.displayFiles = [...this.files];

					uni.showToast({
						title: '移动成功',
						icon: 'success'
					});
				} catch (error) {
					if (error.message !== '用户取消') {
						console.error('移动文件失败:', error);
						uni.showToast({
							title: '移动失败',
							icon: 'none'
						});
					}
				} finally {
					this.closeFileOptions();
				}
			}
		}
	}
</script>

<style>
	@import '@/static/font_4719143_73svg6uhuri/iconfont.css';

	/* 搜索区域样式 */
	.search_area {
		padding: 10px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	/* 文件列表样式 */
	.file-list {
		padding: 10px;
		background-color: #f8f8f8;
	}

	.file-item {
		display: flex;
		align-items: center;
		padding: 15px;
		background-color: #fff;
		border-radius: 8px;
		margin-bottom: 10px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.file-name {
		flex: 1;
		padding: 0 10px;
		font-size: 14px;
		color: #333;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.file_info {
		min-width: 120px;
		font-size: 12px;
		color: #666;
	}

	.actions {
		display: flex;
		gap: 15px;
		align-items: center;
	}

	/* 弹窗样式 */
	.popup-content {
		background-color: #fff;
		border-radius: 16px 16px 0 0;
		padding: 20px;
	}

	.popup-title {
		text-align: center;
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 20px;
	}

	.popup-item {
		display: flex;
		align-items: center;
		padding: 15px 0;
		font-size: 14px;
		border-bottom: 1px solid #eee;
	}

	.popup-item text {
		margin-left: 10px;
	}

	.warning {
		color: #ff4d4f;
	}

	.popup-cancel {
		text-align: center;
		padding: 15px 0;
		color: #666;
		font-size: 14px;
	}

	.preview-content {
		background-color: #fff;
		border-radius: 8px;
		width: 90vw;
		max-height: 80vh;
		overflow: hidden;
	}

	.preview-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.preview-title {
		font-size: 16px;
		font-weight: 500;
		flex: 1;
		margin-right: 10px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.preview-body {
		min-height: 200px;
		max-height: 60vh;
		position: relative;
	}

	.preview-image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.preview-pdf,
	.preview-office {
		width: 100%;
		height: 60vh;
	}

	.unsupported-preview {
		padding: 32px 16px;
		text-align: center;
	}

	.download-btn {
		margin-top: 16px;
		background-color: #007AFF;
		color: #fff;
		padding: 8px 16px;
		border-radius: 4px;
		font-size: 14px;
	}

	/* 添加按钮样式 */
	.add-button {
		position: fixed;
		right: 20px;
		bottom: 20px;
		width: 50px;
		height: 50px;
		background-color: #007AFF;
		border-radius: 25px;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
	}

	/* 	.custom-navbar {
	  display: flex;
	  align-items: center;
	  padding: 10px;
	  background-color: #fff;
	  position: fixed;
	  width: 100%;
	  top: 0;
	  z-index: 999;
	} */
</style>